package com.hejing.Collection子接口Set;

import java.util.Objects;

/**
 * ClassName: User
 * Package: com.hejing.Collection子接口Set
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-05-18 17:14
 * @Version: 1.0
 */
public class User implements Comparable{

    private String name;
    private int age;

    public User() {

    }



    public User(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("use equals()方法....");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    // 重写compareTo()方法;

    /**
     * 按照年龄从小到大排序
     * @param o
     * @return
     */
   /* @Override
    public int compareTo(Object o) {
        if(this == o) return 0;
        if(o instanceof User) {
            User u = (User)o;
            return this.age - u.age;
        }
        throw new RuntimeException("类型不匹配");
    }*/

    /**
     * 先比较年龄（从小到大），如果年龄相同，继续比较姓名（从大到小）
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Object o) {
        if(this == o) return 0;
        if(o instanceof User) {
            User u = (User)o;
            int ageValue = this.age - u.age;
            if(ageValue != 0) return ageValue;
            return -this.name.compareTo(u.name);
        }
        throw new RuntimeException("类型不匹配");
    }
}


















